package com.springboot.util.common;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @description:
 * @author: zyj
 * @create: 2020-08-13 16:12
 **/
@Slf4j
public class MyStreamUtil {

    public static OutputStream openOutPutStreamExcel(HttpServletResponse response, String filename) {
        response.setContentType("application/vnd.ms-excel");
        return openOutPutStream(response, filename,  "xls");
    }

    public static OutputStream openOutPutStreamExcels(HttpServletResponse response, String filename) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf-8");
        return openOutPutStream(response, filename,  "xlsx");
    }

    public static OutputStream openOutPutStream(HttpServletResponse response, String filename, String fileType) {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename,"UTF-8")+"."+fileType);
            out = response.getOutputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out;
    }


    public static void close(Object obj) {
        if (obj != null) {
            try {
                if (obj instanceof InputStream) {
                    ((InputStream) obj).close();
                } else if (obj instanceof OutputStream) {
                    ((OutputStream) obj).close();
                } else if (obj instanceof ByteArrayOutputStream) {
                    ((ByteArrayOutputStream) obj).close();
                } else if (obj instanceof FileOutputStream) {
                    ((FileOutputStream) obj).close();
                }
            } catch (IOException e) {
                log.error("MyStreamUtil close", e);
            }

        }
    }

    /**
     * description: 复制数组
     *
     * @return: byte
     * @author: zyj
     */
    public static byte[] byteCopy(byte[] data) {
        byte[] result = new byte[data.length];
        System.arraycopy(data, 0, result, 0, data.length);
        return result;
    }
}
